package com.jamal2362.apktool.util.as;

import java.io.File;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

public class JsonMerger
{
	public static JSONObject jsonMerge(JSONObject source, JSONObject target) throws JSONException
	{
		Iterator<String> keys = target.keys();
		while (keys.hasNext())
		{
			String key =  keys.next();
			if (source.has(key))
			{
				if (target.isNull(key))
					continue;
				Object val1 = source.get(key);
				Object val2 = target.get(key);
				if (val1.equals(val2))
					continue;
				if (val2 instanceof JSONObject)
				{
					if (val1 instanceof JSONObject)
					{
						JSONObject t = (JSONObject) val2;
						if (t.length() == 0)
							continue;
						source.put(key, jsonMerge((JSONObject)val1, (JSONObject)val2));
					}
					else
					{
						source.put(key, target.get(key));
					}
				}
				else if (val2 instanceof JSONArray)
				{
					if (val1 instanceof JSONArray)
					{
						JSONArray t = (JSONArray) val2;
						if (t.length() == 0)
							continue;
						source.put(key, jsonArrMerge((JSONArray)val1, (JSONArray)val2));
					}
					else
					{
						source.put(key, target.get(key));
					}
				}
				else
				{
					source.put(key, target.get(key));
				}
			}
			else
			{
				source.put(key, target.get(key));
			}
		} 
		return source;
	}

	public static JSONArray jsonArrMerge(JSONArray source, JSONArray target)
	{
		for (int i = 0; i < target.length(); i++)
		{
			try
			{
				Object val2 = target.get(i);
				if (hasObj(source, val2))
					continue;
				source.put(target.get(i));
			}
			catch (JSONException e)
			{

			}
		}
		return source;
	}

	public static boolean hasObj(JSONArray ja, Object obj)
	{
		for (int i = 0; i < ja.length(); i++)
		{
			try
			{
				if (ja.get(i).equals(obj))
				{
					return true;
				}
			}
			catch (JSONException e)
			{}
		}
		return false;
	}

	public static JSONObject fromFile(File file)
	{
		String string = ASUtils.readToString(file);
		try
		{
			return new JSONObject(string);
		}
		catch (JSONException e)
		{
			return null;
		}
	}

	public static void writeToFile(File file, JSONObject obj)
	{
		String str = obj.toString();
		ASUtils.writeToFile(file, str);
	}
}
